const { app, BrowserWindow } = require('electron');
const path = require('path');
// const { spawn } = require('child_process');

let mainWindow;
// let serverProcess;

function createWindow () {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false, // 允许加载本地文件
            allowRunningInsecureContent: true
        },
        icon: path.join(__dirname, '../public/favicon.ico'),
        show: false, // 先隐藏窗口，加载完成后再显示
        titleBarStyle: 'default',
        resizable: true,
        minimizable: true,
        maximizable: true
    });
    
    // 修正：打包后用 process.cwd()，开发环境用 __dirname
    const isDev = !app.isPackaged;
    const indexPath = isDev
        ? path.join(__dirname, '../dist/index.html')
        : path.join(__dirname, '../dist/index.html');

    console.log("加载文件路径:", indexPath);
    console.log(" 文件是否存在:", require('fs').existsSync(indexPath));
    
    mainWindow.loadFile(indexPath).then(r =>{
        console.log('启动后端服务');
    } );
    
    // 监听页面加载事件
    mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
        console.error('页面加载失败:', errorCode, errorDescription, validatedURL);
    });
    
    mainWindow.webContents.on('did-finish-load', () => {
        console.log('页面加载完成');
    });
    
    // 窗口准备好后显示
    mainWindow.once('ready-to-show', () => {
        mainWindow.show();
        console.log('窗口已显示');
    });
    
    // 开发环境下打开开发者工具
    if (isDev) {
        mainWindow.webContents.openDevTools();
    }
    
    // 处理窗口关闭事件
    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

function startServer() {
    try {
        // 直接在主进程 require 后端服务
        require('../nodeexpress/app.js');
        console.log('✅ 后端服务启动成功');
    } catch (error) {
        console.error('❌ 后端服务启动失败:', error);
    }
}

app.whenReady().then(() => {
    startServer();
    createWindow();
    
    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit();
});

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
});

// app.on('before-quit', () => {
//     if (serverProcess) {
//         serverProcess.kill();
//     }
// }); 